<?php
// Caclulate basepath
$basepath =  substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos( $_SERVER['SCRIPT_FILENAME'], "/modules/pageparts/direct" ));
// Get config files
$registry_cache_file = $basepath."/etc/cached_config.ini";
$registry_cache = parse_ini_file($registry_cache_file);
$config = parse_ini_file($basepath."/etc/config.ini", true);


$filename = $_GET['filename'];
try{
	if(array_key_exists('size_x',$_GET)){
		$size_x = $_GET['size_x'];
	} else {
		$size_x = 600;
	}
	
	if(array_key_exists('size_y',$_GET)){
		$size_y = $_GET['size_y'];
	} else {
		$size_y = 600;
	}
	
	if(array_key_exists('crop',$_GET)){
		$crop = (boolean)$_GET['crop'];	
	} else {
		$crop = false;
	}
	
	
	$missing_image 	= $registry_cache['default.missing_image'];
	$image 			= $basepath.$filename;
	
	if (strrchr($image, '/')) {
		$filename = substr(strrchr($image, '/'), 1); // remove folder references
	} else {
		$filename = $image;
	}
	
	
	$file_dest_path = "";				
	for($x=0; $x < 3; $x++){
		$file_dest_path .=  substr($filename,$x,1)  . "/";
	}
	
	$cache_dir 		= $config['application']['image_cache_dir']."/pageparts/".$file_dest_path;
	
	if (!file_exists($image)) {
		$cache_dir = $config['application']['image_cache_dir']."/";
		$filename = "missing";
		$image = $missing_image;
	}
	
	if(!is_dir($cache_dir)){
		mkdir($cache_dir,0777,true);
	}
	
	$prefix = $size_x . "_" . $size_y . "_";
	
	if($crop){
		$prefix .= "crop_";
	}
	
	$resized = $cache_dir.$prefix.$filename;
	
	if (!is_dir($cache_dir)) {
		mkdir($cache_dir, 0777, true);
	}
	if (!file_exists($resized)) {
		//die($image);
		set_include_path(get_include_path().PATH_SEPARATOR.$basepath."/modules/default/lib");
		set_include_path(get_include_path().PATH_SEPARATOR.$config['application']['asido_path']);
		define('ASIDO_DIR', null);
		@include('class.asido.php');
		@asido::driver('gd_c');
		$i1 = @asido::image($image, $resized);
		if($crop){	
			// we now assume original image will be 4:3.	
			@asido::width($i1,$size_x);			
		}else{
			@asido::fit($i1, $size_x, $size_y);
		}
		
		@asido::convert($i1, 'image/jpeg');
		@$i1->save(ASIDO_OVERWRITE_ENABLED);
	}
	@header("Content-Length: ".filesize($resized));
	header("Expires: ". date(DATE_RFC1123,strtotime("+2 months")) );
	header("Accept-Ranges: bytes");
	header("ETag: " . md5($resized));
	header("Content-type: image/jpeg");
	@readfile($resized);
} catch (Exception $e){
	
	
}
exit;
